package com.example.net.bean.gson;

import com.example.net.bean.BaseBean;
import com.example.net.error.ResultException;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        //value服务器传回给我们的body value有自己的string方法  一定不能使用toString
        String response = value.string();

        //构建泛型的type BaseBean<type>
        Type baseBeanType = $Gson$Types.newParameterizedTypeWithOwner(null, BaseBean.class, type);

        BaseBean baseBean = gson.fromJson(response, baseBeanType);
        if (baseBean.isError()) {
            throw  new ResultException(baseBean.getMsg(), baseBean.getCode());
        } else {
            //成功返回继续用原来的Type解析得到data数据强制转换后发送出去
            return (T) baseBean.getResults();
        }

    }

}